package com.tanhua.server.server;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.FocusApi;
import com.tanhua.dubbo.api.FocusUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domian.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Focus;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.FocusVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FocusUserApi focusUserApi;

    @DubboReference
    private FocusApi focusApi;


    /**
     * 发布小视频
     *
     * @param videoThumbnail
     * @param videoFile
     */
    /*  @CacheEvict(value="videos",allEntries = true)*/
    public void saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //先判断文件是否为空
        if (videoThumbnail.isEmpty() || videoFile.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }
        //将视频上传到fastDFS，获取访问url
        String filename = videoFile.getOriginalFilename();
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = fastFileStorageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        //文件路径
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //图片上传到OSS及路径
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());

        //构建video对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("java,从入门到入土");
        //调用Api保存
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }
    }

    /*    @Cacheable(
                value = "videos",
                ////userid_page_pagesize
                key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page+'_'+#pagesize"
        )*/
    public PageResult videosList(Integer page, Integer pagesize) {
        //从redis里面找推荐列表
        String key = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String redisvalue = redisTemplate.opsForValue().get(key);
        //判断redis数据是否存在，判断redis中数据是否满足本次分页条数
        List<Video> list = new ArrayList<>();
        int redispage = 0;
        if (!StringUtils.isEmpty(redisvalue)) {
            String[] split = redisvalue.split(".");
            //判断当前页的起始条数是否小于数组总数
            if ((page - 1) * pagesize < split.length) {
                List<Long> videos = Arrays.stream(split).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e -> Long.valueOf(e))
                        .collect(Collectors.toList());
                // 调用API根据PID数组查询动态数据
                list = videoApi.findMovementsByVids(videos);
            }
            redispage = PageUtil.totalPage(split.length, pagesize);
        }
        //如果没有就从mongdb里面找,如果redis数据不存在，分页查询视频数据
        if (list.isEmpty()) {
            //page的计算规则，  传入的页码  -- redis查询的总页数
            list = videoApi.queryVideoList(page - redispage, pagesize);
        }
        //然后根据video里面的userid查询userinfo表找到视频作者信息
        List<Long> userId = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userId, null);
        //封装videovo返回
        ArrayList<VideoVo> videoVos = new ArrayList<>();
        for (Video video : list) {
            UserInfo userInfo = userInfoMap.get(video.getUserId());
            if (userInfo != null) {
                VideoVo init = VideoVo.init(userInfo, video);

                //从redis里面取出关注列表展示到页面
                String key1 = Constants.User_FOCUS_KEY + UserHolder.getUserId();
                String hashKey = Constants.User_Follw_Hash_Key + video.getUserId();
                if (redisTemplate.opsForHash().hasKey(key1, hashKey)) {
                    init.setHasFocus(1);
                }
                String likekey = Constants.User_FOCUS_KEY + video.getId().toString();
                String likehashKey = Constants.FOCUS_like_Hash_Key + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(likekey, likehashKey)) {
                    init.setHasLiked(1);
                }


                videoVos.add(init);
            }
        }
        return new PageResult(page, pagesize, 0, videoVos);
    }

    public void userFocus(Long uid) {
        //调用Api保存关注,并且
        focusUserApi.saveFollow(UserHolder.getUserId(), uid);
        //用redis缓存hash结构
        String key = Constants.User_FOCUS_KEY + UserHolder.getUserId();
        String hashKey = Constants.User_Follw_Hash_Key + uid;

        redisTemplate.opsForHash().put(key, hashKey, "1");
    }

    public void userUnFocus(Long uid) {
        //调用Api删除关注
        focusUserApi.deleteFollow(UserHolder.getUserId(), uid);
        //删除redis关注数据
        String key = Constants.User_FOCUS_KEY + UserHolder.getUserId();
        String hashKey = Constants.User_Follw_Hash_Key + uid;
        redisTemplate.opsForHash().delete(key, hashKey);
    }

    /**
     * 视频点赞
     *
     * @param uid
     * @return
     */
    public Integer Focuslike(String uid) {
        //查询是否已经点了喜欢
        Boolean value = focusApi.queryFocuslike(UserHolder.getUserId(), uid, CommentType.LIKE.getType());
        if (value) {
            throw new BusinessException(ErrorResult.error());
        }
        //往focus表添加点赞数据，更新video表的点赞数+1返回
        Focus focus = new Focus();
        focus.setCommentType(CommentType.LIKE.getType());
        focus.setUserId(UserHolder.getUserId());
        focus.setPublishId(new ObjectId(uid));
        focus.setCreated(System.currentTimeMillis());
        Integer all = focusApi.saveFocuslike(focus);
        //往redis里面添加缓存
        String key = Constants.User_FOCUS_KEY + uid;
        String hashKey = Constants.FOCUS_like_Hash_Key + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return all;
    }

    /**
     * 视频取消喜欢
     *
     * @param uid
     * @return
     */
    public Integer Focusdislike(String uid) {
        //查询是否已经点了喜欢
        Boolean value = focusApi.queryFocuslike(UserHolder.getUserId(), uid, CommentType.LIKE.getType());
        if (!value) {
            throw new BusinessException(ErrorResult.error());
        }
        //往focus表删除点赞数据，更新video表的点赞数-1返回
        Focus focus = new Focus();
        focus.setCommentType(CommentType.LIKE.getType());
        focus.setUserId(UserHolder.getUserId());
        focus.setPublishId(new ObjectId(uid));
        focus.setCreated(System.currentTimeMillis());
        Integer all = focusApi.deleteFocusdislike(focus);
        //往redis里面删除缓存
        String key = Constants.User_FOCUS_KEY + uid;
        String hashKey = Constants.FOCUS_like_Hash_Key + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return all;

    }

    /**
     * 视频评论列表
     *
     * @param uid
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findFocusd(String uid, Integer page, Integer pagesize) {
        //根据视频id找到 focus表里面评论的数据 评论人
        List<Focus> ids = focusApi.queryFocus(uid, page, pagesize, CommentType.COMMENT.getType());
        if (CollUtil.isEmpty(ids)) {
            return new PageResult();
        }
        //找到所有评论人
        List<Long> userIds = CollUtil.getFieldValues(ids, "userId", Long.class);
        //根据评论人ID找到评论人信息
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, null);
        //封装VO后返回
        ArrayList<FocusVo> FocusVos = new ArrayList<>();
        for (Focus focus : ids) {
            UserInfo userInfo = userInfoMap.get(focus.getUserId());
            if (userInfo != null) {
                FocusVo init = FocusVo.init(userInfo, focus);


                String key = Constants.User_FOCUS_KEY + focus.getId().toString();
                String hashKey = Constants.FOCUS_Comment_like_Hash_Key + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key,hashKey)) {
                    init.setHasLiked(1);
                }


                FocusVos.add(init);
            }
        }
        return new PageResult(page, pagesize, 0, FocusVos);
    }

    /**
     * 视频评论点赞
     * @param id
     * @return
     */
    public Integer focusCommentsLike(String id) {
        Focus focus = new Focus();
        focus.setPublishId(new ObjectId(id));
        focus.setUserId(UserHolder.getUserId());
        focus.setCommentType(CommentType.LIKE.getType());
        focus.setCreated(System.currentTimeMillis());
        //判断是否已经点赞
        boolean result = focusApi.queruFocusCommentsLike(focus);
        if (result) {
            throw new BusinessException(ErrorResult.error());
        }
        //在foucs表里面添加点赞数据，并且更新评论的点赞数
        Integer all = focusApi.saveFocusCommentsLike(focus);
        //将视频点赞存入redis
        String key = Constants.User_FOCUS_KEY + id;
        String hashKey = Constants.FOCUS_Comment_like_Hash_Key + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return all;
    }


    public Integer focusCommentsDislike(String id) {
        Focus focus = new Focus();
        focus.setPublishId(new ObjectId(id));
        focus.setUserId(UserHolder.getUserId());
        focus.setCommentType(CommentType.LIKE.getType());
        //判断是否已经点赞,如果未点赞则抛出异常
        boolean result = focusApi.queruFocusCommentsLike(focus);
        if (!result) {
            throw new BusinessException(ErrorResult.error());
        }
        //删除foucs里面本条点赞的数据，并且更新评论
        Integer all = focusApi.DeleteFocusCommentsLike(focus);
        //删除redis
        String key = Constants.User_FOCUS_KEY + id;
        String hashKey = Constants.FOCUS_Comment_like_Hash_Key + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return all;
    }
}
